Completed
Push — development ( 913816...c4bf15 )
by Nils
08:04
created

functions.js ➔ jsonErrorHdl   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
nc 1
nop 1
dl 0
loc 8
rs 9.4285
c 0
b 0
f 0
1
/**
2
 * @file          functions.js
3
 * @author        Nils Laumaillé
4
 * @version       2.1.27
5
 * @copyright     (c) 2009-2017 Nils Laumaillé
6
 * @licensing     GNU AFFERO GPL 3.0
7
 * @link          http://www.teampass.net
8
 *
9
 * This library is distributed in the hope that it will be useful,
10
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
12
 */
13
14
/**
15
*   Show or hide Loading animation GIF
16
**/
17
function LoadingPage(){
18
    if ( $("#div_loading").is(':visible') )
19
        $("#div_loading").hide();
20
    else
21
        $("#div_loading").show();
22
}
23
24
/**
25
*   Reload a page
26
**/
27
function RefreshPage(myform){
28
    document.forms[myform].submit();
29
}
30
31
/**
32
*   Add 1 hour to session duration
33
**/
34
function IncreaseSessionTime(message_end, message_wait, duration){
35
    duration = duration || 60;
36
    $("#main_info_box_text").html(message_wait);
37
    $("#main_info_box").show().position({
38
        my: "center",
39
        at: "center top+75",
40
        of: "#top"
41
    });
42
    $.post(
43
        "sources/main.queries.php",
44
        {
45
        type    : "increase_session_time",
46
        duration: parseInt(duration) * 60
47
        },
48
        function(data){
49
            if (data[0].new_value != "expired") {
50
                $("#main_info_box_text").html(message_end);
51
                setTimeout(function(){$("#main_info_box").effect( "fade", "slow" );}, 1000);
52
                $("#temps_restant").val(data[0].new_value);
53
                $("#date_end_session").val(data[0].new_value);
54
                $('#countdown').css("color","white");
55
                $("#div_increase_session_time").dialog("close");
56
            } else {
57
                document.location = "index.php?session=expired";
58
            }
59
        },
60
        "json"
61
    );
62
}
63
64
/**
65
*   Countdown before session expiration
66
**/
67
function countdown()
68
{
69
    var DayTill
70
    var theDay =  $('#temps_restant').val();
71
    var today = new Date(); //Create an Date Object that contains today's date.
72
    var second = Math.floor(theDay - (today.getTime()/1000));
73
    var minute = Math.floor(second/60); //Devide "second" into 60 to get the minute
74
    var hour = Math.floor(minute/60); //Devide "minute" into 60 to get the hour
75
    var CHour= hour % 24; //Correct hour, after devide into 24, the remainder deposits here.
76
    if (CHour<10) {
77
        CHour = "0" + CHour;
78
    }
79
    var CMinute= minute % 60; //Correct minute, after devide into 60, the remainder deposits here.
80
    if (CMinute<10) {
81
        CMinute = "0" + CMinute;
82
    }
83
    var CSecond= second % 60; //Correct second, after devide into 60, the remainder deposits here.
84
    if (CSecond<10) {
85
        CSecond = "0" + CSecond;
86
    }
87
    DayTill = CHour+":"+CMinute+":"+CSecond;
88
89
    //Avertir de la fin imminante de la session
90
    if ( DayTill == "00:01:00" ){
91
        $('#div_increase_session_time').dialog('open');
92
        $('#countdown').css("color","red");
93
    }
94
95
    // Manage end of session
96
    if ($("#temps_restant").val() != "" && DayTill <= "00:00:00" && $("#please_login").val() != 1) {
97
        $("#please_login").val("1");
98
        document.location = "index.php?session=expired";
99
    }
100
101
    //Rewrite the string to the correct information.
102
    if ($('#countdown')){
103
        $('#countdown').html(DayTill); //Make the particular form chart become "Daytill"
104
    }
105
106
    //Create the timer "counter" that will automatic restart function countdown() again every second.
107
    setTimeout(
108
        function() {
109
            countdown();
110
        },
111
        1000
112
    );
113
}
114
115
/**
116
*   Open a dialog
117
**/
118
function OpenDialog(id){
119
    $('#'+id).dialog('open');
120
}
121
122
/**
123
*   Toggle a DIV
124
**/
125
function toggleDiv(id){
126
    $('#'+id).slideToggle("slow");
127
    //specific case to not show upgrade alert
128
    if(id == "div_maintenance"){
129
        $.post(
130
            "sources/main.queries.php",
131
            {
132
            type    : "hide_maintenance"
133
            }
134
        );
135
    }
136
}
137
138
/**
139
*   Checks if value is an integer
140
**/
141
function isInteger(s) {
142
  return (s.toString().search(/^-?[0-9]+$/) == 0);
143
}
144
145
/**
146
*   Generate a random string
147
**/
148
function CreateRandomString(size,type){
149
    var chars = "";
150
151
    // CHoose what kind of string we want
152
    if ( type == "num" ) chars = "0123456789";
153
    else if ( type == "num_no_0" ) chars = "123456789";
154
    else if ( type == "alpha" ) chars = "ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz";
155
    else if ( type == "secure" ) chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz&#@;!+-$*%";
156
    else chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz";
157
158
    //generate it
159
    var randomstring = '';
160
    for (var i=0; i<size; i++) {
161
        var rnum = Math.floor(Math.random() * chars.length);
162
        randomstring += chars.substring(rnum,rnum+1);
163
    }
164
165
    //return
166
    return randomstring;
167
}
168
169
170
/**
171
*
172
**/
173
function unsanitizeString(string){
174
    if(string != "" && string != null){
175
        string = string.replace(/\\/g,'').replace(/&#92;/g,'\\');
176
    }
177
    return string;
178
}
179
180
/**
181
*   Clean up a string and delete any scripting tags
182
**/
183
function sanitizeString(string){
184
    if(string != "" && string != null){
185
        string = string.replace(/\\/g,'&#92;').replace(/"/g,"&quot;");
186
        string = string.replace(new RegExp('\\s*<script[^>]*>[\\s\\S]*?</script>\\s*','ig'),'');
187
    }
188
    return string;
189
}
190
191
/**
192
*   Send email
193
**/
194
function SendMail(cat, content, key, message){
195
    $.post(
196
        "sources/items.queries.php",
197
        {
198
            type    : "send_email",
199
            cat     : cat,
200
            content : content,
201
            key     : key
202
        },
203
        function(data){
204
            if (data[0].error !== undefined && data[0].error !== "") {
205
                message = data[0].message;
206
            }
207
            $("#div_dialog_message_text").html(message);
208
            $("#div_dialog_message").dialog("open");
209
        },
210
        "json"
211
    );
212
}
213
214
/**
215
*   Checks if email has expected format ([email protected])
216
**/
217
function IsValidEmail(email){
218
    var filter = /^([\w-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/;
219
    return filter.test(email);
220
}
221
222
/**
223
*   Checks if URL has expected format
224
**/
225
function validateURL(textval) {
226
    //var urlregex = new RegExp("^(http:\/\/www.|https:\/\/www.|ftp:\/\/www.|www.){1}([0-9A-Za-z]+\.)");
227
    var urlregex = /(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/;
228
    return urlregex.test(textval);
229
}
230
231
232
function split( val ) {
233
    return val.split( / \s*/ );
234
}
235
236
function extractLast( term ) {
237
    return split( term ).pop();
238
}
239
240
241
function store_error(message_error, dialog_div, text_div){
242
    //Store error in DB
243
    $.post(
244
        "sources/main.queries.php",
245
        {
246
            type    : "store_error",
247
            error   : escape(message_error)
248
        }
249
    );
250
    //Display
251
    $("#"+text_div).html("An error appears. Answer from Server cannot be parsed!<br />Returned data:<br />"+message_error);
252
    $("#"+dialog_div).dialog("open");
253
}
254
255
function aes_encrypt(text, key)
256
{
257
    return Aes.Ctr.encrypt(text, key, 256);
258
}
259
260
261
function aes_decrypt(text, key)
262
{
263
    return Aes.Ctr.decrypt(text, key, 256);
264
}
265
266
function prepareExchangedData(data, type, key)
267
{
268
    var jsonResult;
0 ignored issues
show
Unused Code introduced by
The variable jsonResult seems to be never used. Consider removing it.
Loading history...
269
    if (type == "decode") {
270
        if ($("#encryptClientServer").val() == 0) {
271
            try {
272
                return $.parseJSON(data);
273
            }
274
            catch (e) {
275
                return "Error: " + jsonErrorHdl(e);
276
            };
277
        } else {
278
            try {
279
                return $.parseJSON(aes_decrypt(data, key));
280
            }
281
            catch (e) {
282
                return "Error: " + jsonErrorHdl(e);
283
            };
284
        }
285
    } else if (type == "encode") {
286
        if ($("#encryptClientServer").val() == 0) {
287
            return data;
288
        } else {
289
            return aes_encrypt(data, key);
290
        }
291
    } else {
292
        return false;
293
    }
294
}
295
296
function jsonErrorHdl(message)
297
{
298
    $("#div_dialog_message_text").html(message);
299
    $("#div_dialog_message").dialog("open");
300
    $("#items_path_var").html('<i class="fa fa-folder-open-o"></i>&nbsp;Error');
301
    $("#items_list_loader").hide();
302
    return false;
303
}
304
305
function displayMessage(textToDisplay)
306
{
307
    $("#main_info_box_text").html(textToDisplay);
308
    $("#main_info_box").show().position({
309
        my: "center",
310
        at: "center top+20",
311
        of: "#main_simple"
312
    });
313
    setTimeout(function(){$("#main_info_box").effect( "fade", "slow");}, 2000);
314
}
315
316
317
function blink(elem, times, speed, klass)
318
{
319
    if (times > 0 || times < 0) {
320
      if ($(elem).hasClass(klass))
321
         $(elem).removeClass(klass);
322
      else
323
         $(elem).addClass(klass);
324
     }
325
326
     clearTimeout(function() { blink(elem, times, speed, klass); });
327
328
     if (times > 0 || times < 0) {
329
       setTimeout(function() { blink(elem, times, speed, klass); }, speed);
330
       times-= .5;
331
     }
332
}